<?php
session_start();
error_reporting(0);
set_time_limit(0);
header('Content-type: text/html; charset=utf-8');
isset($_SESSION['member']) && $_SESSION['member'] = null;
$AppID = 'wx331ed6d859b117cb';
$AppSecret = 'dbada5df9c35c886582d7a0d05fe3a2c';
if (isset($_GET['code']) && $_GET['code']) {
    // 用户同意授权
    // 获取access_token
    $json = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$AppID}&secret={$AppSecret}&code={$_GET['code']}&grant_type=authorization_code");
    $result = json_decode($json, true);
//    _log($result);
    isset($result['errcode']) && exit($result['errmsg']);

    // 获取用户信息
    $json = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token={$result['access_token']}&openid={$result['openid']}&lang=zh_CN");
    $result = json_decode($json, true);
//    _log($result);
    isset($result['errcode']) && exit($result['errmsg']);
    $_SESSION['member'] = $result;
    $redirect_url = $_SESSION['weixin_redirect_uri'] ? $_SESSION['weixin_redirect_uri'] : ('HTTP://' . $_SERVER['HTTP_HOST'] . '/index.php?s=/Wap/Store/index');
    header('Location: ' . $redirect_url);        // 在这里可以设置跳转
} elseif (isset($_GET['state']) && !(isset($_GET['code']) && $_GET['code'])) {
    // 用户禁止授权
    exit('请同意授权');
} else {
    // 申请用户授权
    $redirect_uri = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']);
    $_SESSION['weixin_redirect_uri'] = $_SERVER['HTTP_REFERER'];
    $response_type = 'code';
    $scope = 'snsapi_userinfo';
    header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid={$AppID}&redirect_uri={$redirect_uri}&response_type={$response_type}&scope={$scope}&state=STATE#wechat_redirect");
}

function _log($val) {
    $file = './log.txt';
    $string = '时间: ' . date('Y-m-d H:i:s') . "\r\n";
    $string .= print_r($val, true);
    $string .= "\r\n";
    $string .= "========================================================\r\n";
    file_put_contents($file, $string, FILE_APPEND);
}